package com.xzq.rongimtest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;

import io.rong.imkit.ConversationEventListener;
import io.rong.imkit.RongIM;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String rongCloudUserId = "user9";
        SharedPreferences.Editor editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit();
        editor.putString("id", rongCloudUserId);
        editor.apply();

        //获取融云token
        getToken();

        Button button = findViewById(R.id.show_token);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                token = getSharedPreferences("data", Context.MODE_PRIVATE).getString("rongYunToken", null);
                if(token != null){
                    connectRongIM(token);
                }
            }
        });

        Button button1 = findViewById(R.id.open_conversation_list);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ConversationListActivity.class);
                startActivity(intent);
            }
        });

        Button button2 = findViewById(R.id.send_message);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Conversation.ConversationType  conversationType = Conversation.ConversationType.PRIVATE;
                String targetId = "user19";
                String title = "黄埔胡歌";
                long fixedMsgSentTime = Calendar.getInstance().getTimeInMillis();
                Bundle bundle = new Bundle();
                if(!TextUtils.isEmpty(title)){
                    bundle.putString(RouteUtils.TITLE, title);
                    bundle.putLong(RouteUtils.INDEX_MESSAGE_TIME, fixedMsgSentTime);
                }
                RouteUtils.routeToConversationActivity(getApplicationContext(), conversationType, targetId, bundle);
            }
        });

    }

    /**
     * 连接IM
     */
    private void connectRongIM(String token){
        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onSuccess(String s) {
                LogUtils.i("连接成功");
            }

            @Override
            public void onError(RongIMClient.ConnectionErrorCode connectionErrorCode) {
                if(connectionErrorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONN_TOKEN_INCORRECT)){
                    getToken();
                    String newToken = getSharedPreferences("data", Context.MODE_PRIVATE).getString("rongYunToken", null);
                    connectRongIM(newToken);
                }else{
                    ToastUtils.showLong("无法连接到服务器,请稍后重试");
                }
            }

            @Override
            public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus databaseOpenStatus) {

            }
        });
    }

    private void getToken(){
        String url = "https://api-cn.ronghub.com/user/getToken.json";
        String userId = getSharedPreferences("data", Context.MODE_PRIVATE).getString("id", null);
        String name = "广州吴彦祖";
        String portraitUri = "http://qn.myas.maissy.net/202105/19/CC41DADA-702E-2AF0-CFEC-24FF6EB93214.jpg";
        RequestBody body = new FormBody.Builder()
                .add("userId", userId)
                .add("name", name)
                .add("portraitUri", portraitUri)
                .build();
        new Thread(){
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.postWithHeaders(url, body);
                    RongYunTokenResponseModel model = new Gson().fromJson(response.body().string(), RongYunTokenResponseModel.class);
                    if(model.getCode() == 200){
                        SharedPreferences.Editor editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit();
                        editor.putString("rongYunToken", model.getToken());
                        editor.apply();
                    }else{
                        ToastUtils.showShort(model.getErrorMessage());
                    }
                }catch (IOException | NoSuchAlgorithmException e){
                    e.printStackTrace();
                }
            }
        }.start();
    }
}